"use strict";

const Controller = require("./baseController");
const crypto = require("crypto");
/**
 * @controller UserService 用户接口
 */
class UserController extends Controller {
  
  /**
   * @summary  登陆
   * @description 登陆
   * @router post /user/login
   * @request body Login
   * @response 200 JsonResult 操作结果
   */
  async login() {
    const { ctx, service } = this;
    // 参数验证
    let { username, password } = ctx.request.body;
    // 验证该用户是否存在|验证该用户状态是否启用
    let user = await ctx.model.User.findOne({
      where: {
        username,
      },
    });
    if (!user) {
      ctx.throw(400, "用户不存在或已被禁用");
    }
    // 验证密码
    if(password!==user.password){
      ctx.throw(400, "密码错误");
    }
    // await this.checkPassword(password, user.password);

    user = JSON.parse(JSON.stringify(user));
    // 生成token
    let token = ctx.getToken(user);
    user.token = token;
    // 加入缓存中
    if (!(await this.service.cache.set("user_" + user.id, token))) {
      ctx.throw(400, "登录失败");
    }
    delete user.password;
    delete user.id;
    delete user.deleted_time;
    delete user.created_time;
    delete user.updated_time;
    // 返回用户信息和token
    this.jsonBody(user);
  }

  /**
   * @summary   登出
   * @description 登出
   * @router post /user/logout
   * @request body logout
   * @response 200 JsonResult 操作结果
   */
  async logout() {
    const { ctx, service } = this;
    // 拿到当前用户id
    if(!(ctx.authUser&&ctx.authUser.id)){
      ctx.throw(400, "退出登录失败");
    }
    let current_user_id = ctx.authUser.id;
    // 移除redis当前用户信息
    if (!(await service.cache.remove("user_" + current_user_id))) {
      ctx.throw(400, "退出登录失败");
    }
    ctx.apiSuccess("退出成功");
  }

  // 验证密码
  async checkPassword(password, hash_password) {
    // 先对需要验证的密码进行加密
    const hmac = crypto.createHash("sha256", this.app.config.crypto.secret);
    hmac.update(password);
    password = hmac.digest("hex");
    let res = password === hash_password;
    if (!res) {
      this.ctx.throw(400, "密码错误");
    }
    return true;
  }
}

module.exports = UserController;
